package com.bizmerce.rnd.oms.decision.criterion;

import java.util.ArrayList;
import java.util.List;

import com.bizmerce.rnd.oms.decision.data.BillOfMaterials;
import com.bizmerce.rnd.oms.decision.data.HsCode;
import com.bizmerce.rnd.oms.decision.data.RawMaterial;

public abstract class CTCCriterion implements Criterion {

	private List<Criterion> relaxCriterions = null;
	
	public Boolean assign(BillOfMaterials bom) {
		List<RawMaterial> rawMaterials = bom.getRawMaterials();
		HsCode goodsHSCode = bom.getHsCode(); 
		String partOfHSCode = getCode(goodsHSCode);
		
		boolean assignResult = false;
		
		for (RawMaterial material : rawMaterials) {
			if(material.isNotIntraItem()) {
				HsCode materialHSCode = material.getHsCode();
				if(materialHSCode == null) {
					assignResult = false;
					break;
				}
				if(getCode(materialHSCode).equals(partOfHSCode)) {
					assignResult &= false;
				} else {
					assignResult &= true;
					//세번변경기준에 충족하면 역내산으로 인정한다.
//					System.out.println(ToStringBuilder.reflectionToString(material));
					material.setIntraItem(true); //들어온 데이터를 변경하는 것은 문제가 있을 수 있음	
				}
			}
		}
		
		//충족하지 못한 경우 완화 룰을 수행한다.
		//미소 기준이 업는 경우 relax criterion을 등록하지 않는다.
		if(!assignResult && relaxCriterions != null) {
			for (Criterion criterion : relaxCriterions) {
//				System.out.println("--->" + criterion);
				assignResult = criterion.assign(bom);
				if(assignResult) {
					break;
				}
			}
		}
		return assignResult;
	}
	
	public abstract String getCode(HsCode hsCode);

	public void addRelaxRule(Criterion relaxCriterion) {
		if(relaxCriterions == null) {
			relaxCriterions = new ArrayList<Criterion>();
		}
		relaxCriterions.add(relaxCriterion);
	}
}
